import Cookies from 'js-cookie'
import * as Utils from '@/utils/index'
const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    visitedViews: [],
    device: 'desktop'
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state, device) => {
      state.device = device
    },
    ADD_VISITED_VIEWS: (state, view) => {
      // 打开新页签--添加路由数据的方
      if (state.visitedViews.some(v => v.path === view.path)) return
      if (Array.isArray(state.visitedViews) && state.visitedViews.length === 0) {
        if (Array.isArray(Utils.session('visitedViews')) && Utils.session('visitedViews').length !== 0) {
          Utils.session('visitedViews').forEach(view => {
            state.visitedViews.push({
              name: view.name,
              path: view.path,
              isclose: view.name !== '首页'
            })
          })
        } else {
          state.visitedViews.push({
            name: view.name,
            path: view.path,
            isclose: view.name !== '首页'
          })
          Utils.session('visitedViews', state.visitedViews)
        }
      } else {
        state.visitedViews.push({
          name: view.name,
          path: view.path,
          isclose: view.name !== '首页'
        })
        Utils.session('visitedViews', state.visitedViews)
      }
    },
    DEL_VISITED_VIEWS: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews.splice(i, 1)
          break
        }
      }
      Utils.session('visitedViews', state.visitedViews)
    }
  },
  actions: {
    ToggleSideBar: ({ commit }) => {
      commit('TOGGLE_SIDEBAR')
    },
    CloseSideBar({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    addVisitedViews({ commit }, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    ToggleDevice({ commit }, device) {
      commit('TOGGLE_DEVICE', device)
    }
  }
}

export default app
